﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Net;
using System.Text;
using System.Xml;

public class HttpGetLocation : MonoBehaviour
{
    public string gps_info = "";
    public int flash_num = 1;
    public Text location;
    public Text tips;
    public Button btnStop;
    bool stop = true;

    // Use this for initialization
    void Start()
    {
        //StartCoroutine(StartGPS());
        btnStop.onClick.AddListener(StopGPS);
        StartCoroutine(GetWebData(31.21689f, 121.5191f));
    }

    IEnumerator GetWebData(float longitude, float latitude)
    {
        flash_num++;
        //string url = string.Format("http://maps.google.com/maps/api/geocode/xml?latlng={0},{1}&language=zh-CN&sensor=false", longitude, latitude);//31.2151024249, 121.5239493207 谷歌需要翻墙
        string url =string.Format(@"http://api.map.baidu.com/geocoder/v2/?ak=ZndyfXErtTiZQwfgNgQ7yqb7ALKdk4DA&location={0},{1}&output=xml", longitude, latitude);//百度api
        tips.text = url;
        WWW www = new WWW(url);
        yield return www;
        if (www.isDone && www.error == null)
        {
            string pageHtml = Encoding.UTF8.GetString(www.bytes);
            tips.text += pageHtml;
            XmlDocument doc = new XmlDocument();//创建XML文档对象
            if (!string.IsNullOrEmpty(pageHtml))
            {
                doc.LoadXml(pageHtml);//加载xml字符串
                Debug.Log(pageHtml);
                //获取状态信息
                //string xpath = @"GeocodeResponse/status";
                string xpath = @"GeocoderSearchResponse/status";

                XmlNode node = doc.SelectSingleNode(xpath);
                string status = node.InnerText.ToString();
                if (status == "0")
                {
                    //获取地址信息
                    xpath = @"GeocoderSearchResponse/result/formatted_address";
                    node = doc.SelectSingleNode(xpath);
                    string address = node.InnerText.ToString();
                    xpath = @"GeocoderSearchResponse/result/business";
                    node = doc.SelectSingleNode(xpath);
                    location.text = address + node.InnerText.ToString();

                    xpath = @"GeocoderSearchResponse/result/addressComponent";
                    XmlNodeList nodeList = doc.SelectNodes(xpath);
                    XmlNode baseAttribute = nodeList[0].ChildNodes[0];
                    string country = baseAttribute.InnerText;
                    Debug.Log("country:"+ country);
                    baseAttribute = nodeList[0].ChildNodes[1];
                    string countrt_code = baseAttribute.InnerText;
                    Debug.Log("country_code:" + countrt_code);
                    baseAttribute = nodeList[0].ChildNodes[2];
                    string province = baseAttribute.InnerText;
                    Debug.Log("province:" +province);
                    baseAttribute = nodeList[0].ChildNodes[3];
                    string city = baseAttribute.InnerText;
                    Debug.Log("city:"+city);
                    baseAttribute = nodeList[0].ChildNodes[4];
                    string district = baseAttribute.InnerText;
                    Debug.Log("district:"+district);
                    //baseAttribute = nodeList[0].ChildNodes[5];
                    //Debug.Log("邮编:"+baseAttribute.InnerText);
                    baseAttribute = nodeList[0].ChildNodes[6];
                    string street = baseAttribute.InnerText;
                    Debug.Log("street:"+street);


                    tips.text += country+" "+province+" "+city+" "+district +" " + "定位刷新次数:" + flash_num;
                }
            }
            else
            {
                tips.text ="Error:"+www.error.ToString();
            }
        }

    }
    void StopGPS()
    {
        if (stop)
        {
            Input.location.Stop();
            StopAllCoroutines();
            btnStop.GetComponentInChildren<Text>().text = "Start";
        }
        else
        {
            StartCoroutine(StartGPS());
            btnStop.GetComponentInChildren<Text>().text = "Stop";
        }
        stop = !stop;
    }
    
    IEnumerator StartGPS()
    {
        // Input.location 用于访问设备的位置属性（手持设备）, 静态的LocationService位置  
        // LocationService.isEnabledByUser 用户设置里的定位服务是否启用  
        if (!Input.location.isEnabledByUser)
        {
            this.gps_info = "isEnabledByUser value is:" + Input.location.isEnabledByUser.ToString() + " Please turn on the GPS";
            yield return false;
        }

        // LocationService.Start() 启动位置服务的更新,最后一个位置坐标会被使用  
        Input.location.Start(10.0f, 10.0f);

        int maxWait = 20;
        while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
        {
            // 暂停协同程序的执行(1秒)  
            yield return new WaitForSeconds(1);
            maxWait--;
        }

        if (maxWait < 1)
        {
            this.gps_info = "Init GPS service time out";
            yield return false;
        }

        if (Input.location.status == LocationServiceStatus.Failed)
        {
            this.gps_info = "Unable to determine device location";
            yield return false;
        }
        else
        {
            this.gps_info = "N:" + Input.location.lastData.latitude + " E:" + Input.location.lastData.longitude;
            this.gps_info = this.gps_info + " Time:" + Input.location.lastData.timestamp;
            tips.text = this.gps_info;
            //GetLocation(Input.location.lastData.longitude, Input.location.lastData.latitude);
            StartCoroutine(GetWebData(Input.location.lastData.latitude, Input.location.lastData.longitude));
            yield return new WaitForSeconds(3f);
        }
    }

    /// <summary>
    /// 获取位置
    /// </summary>
    /// <param name="longitude">经度</param>
    /// <param name="latitude">纬度</param>
    void GetLocation(float longitude, float latitude)
    {
        string url = string.Format("http://maps.google.com/maps/api/geocode/xml?latlng={0},{1}&language=zh-CN&sensor=false", longitude, latitude);
        WebClient myWebClient = new WebClient();
        myWebClient.Credentials = CredentialCache.DefaultCredentials;
        byte[] pageData = myWebClient.DownloadData(url);
        string pageHtml = Encoding.UTF8.GetString(pageData);
        Debug.Log("pageHtml" + pageHtml);

        location.text = "经度:"+longitude+" 纬度:"+ latitude+" "+ pageHtml;
        if (pageHtml == "")
        {
            return;
        }
        XmlDocument doc = new XmlDocument();//创建XML文档对象

        if (!string.IsNullOrEmpty(pageHtml))
        {
            doc.LoadXml(pageHtml);//加载xml字符串

            //获取状态信息
            string xpath = @"GeocodeResponse/status";
            XmlNode node = doc.SelectSingleNode(xpath);
            string status = node.InnerText.ToString();

            if (status == "OK")
            {
                //获取地址信息
                xpath = @"GeocodeResponse/result/formatted_address";
                node = doc.SelectSingleNode(xpath);
                string address = node.InnerText.ToString();
                location.text = address;
            }
        }
    }
}
